package persistence.logic;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import org.jboss.weld.util.collections.ArraySet;
import persistence.Indexed;

import javax.persistence.*;
import java.lang.reflect.Type;
import java.sql.Timestamp;

/**
 *
 * @author myzone
 */
@Entity
@Table(name = "polls")
public class Poll extends Indexed {

    @ManyToOne
    @JoinColumn(name = "owner")
    protected User owner;

    @Column(name = "creation_timestamp")
    protected Timestamp creationTimestamp;

    @Column(name = "end_timestamp")
    protected Timestamp endTimestamp;

    @OneToMany
    protected List<Question> questions = new ArrayList<>();

    @OneToMany
    protected Set<Opinion> opinions = new ArraySet<>();
    
    @ManyToMany(cascade = CascadeType.ALL)
    protected Map<User, PermissionsPolicy> permissionsPolicies = new HashMap<>();

    public Poll() {
    }

    public Poll(User owner, Timestamp endTimestamp) {
        this.owner = owner;
        this.creationTimestamp = new Timestamp(System.currentTimeMillis());
        this.endTimestamp = endTimestamp;
    }

    public void setOwner(User owner) {
        this.owner = owner;
    }

    public List<Question> getQuestions() {
        return questions;
    }

    public Set<Opinion> getOpinions() {
        return opinions;
    }

    public Map<User, PermissionsPolicy> getPermissionsPolicies() {
        return permissionsPolicies;
    }

    public Timestamp getEndTimestamp() {
        return endTimestamp;
    }

    // json-serilization
    public static Serializer<Poll> getSerializer() {
        return SERIALIZER;
    }
    protected static transient final Serializer<Poll> SERIALIZER = new Serializer<Poll>() {

        @Override
        public JsonElement serialize(Poll src, Type typeOfSrc, JsonSerializationContext context) {
            JsonObject representation = new JsonObject();

            representation.addProperty("id", src.id);
            representation.addProperty("owner", src.owner.getId());
            representation.add("creationTimestamp", context.serialize(src.creationTimestamp));
            representation.add("endTimestamp", context.serialize(src.endTimestamp));
            representation.add("questions", context.serialize(src.questions));
            representation.add("opinions", context.serialize(src.opinions));
            representation.add("permissionsPolicies", context.serialize(src.permissionsPolicies));

            return representation;
        }
    };

}